package com.wanmait.hr.util;


import com.wanmait.hr.vo.User;

import javax.mail.*;
import javax.mail.internet.InternetAddress;

import java.io.InputStream;
import java.util.Date;
import java.util.Properties;
import javax.mail.PasswordAuthentication;
import javax.mail.internet.MimeMessage;

public class MailUtils
{


    public static String FROM = "";
    public static String PASSWORD = "";

    public static boolean sendAuthCodeEmail(User user, String authCode) {
        try {
            Session session = getSession();
            MimeMessage message = new MimeMessage(session);
            Date date = new Date();
            // 设置发送时间
            message.setSentDate(date);
            // 设置邮件主题
            message.setSubject("邮箱验证码邮件", "UTF-8");
            // 设置发件人
            message.setFrom(new InternetAddress(FROM));
            // 设置收件人
            message.setRecipient(Message.RecipientType.TO,
                    new InternetAddress(user.getMail()));
            // 设置右键内容
            message.setContent("Hr管理系统给您发的验证码为:" + authCode,
                    "text/html;charset=utf-8");
            Transport.send(message);
            System.out.println("执行完毕!");
            return  true;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return  false;
        }
    }
    public static Session getSession() throws Exception {
        Properties props = getProperties();
        Authenticator authenticator = new Authenticator() {// 发送邮件帐号权限认证
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(FROM, PASSWORD);
            }
        };
        Session session = Session.getInstance(props, authenticator);
        session.setDebug(true);
        return session;
    }
    public static Properties getProperties() throws Exception {
        Properties props = new Properties();
        InputStream inStream = MailUtils.class.getResourceAsStream("/Email.properties");
        System.out.println("in="+inStream);
        props.load(inStream);
        FROM = props.getProperty("emailfrom");
        PASSWORD = props.getProperty("password");

        return props;
    }

}
